﻿using System;
using System.Windows.Forms;
using Utilities;

namespace WssClient
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //GVar.IniVar();
            //Application.Run(new frmClient());

            //设置应用程序处理异常方式：ThreadException处理
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            //处理UI线程异常
            Application.ThreadException += Application_ThreadException;
            //处理非UI线程异常
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            GVar.IniVar();
            Application.Run(new frmClient());
        }


        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string msg = string.Empty;
            string trace = string.Empty;
            string source = string.Empty;
            if (e.ExceptionObject is System.NullReferenceException)
            {
                var er = (e.ExceptionObject as System.NullReferenceException);
                msg = er.Message;
                trace = er.StackTrace;
                source = er.Source;
            }
            if (e.ExceptionObject is System.InvalidOperationException)
            {
                var es = (e.ExceptionObject as System.InvalidOperationException);
                msg = es.Message;
                msg = es.StackTrace;
                source = es.Source;
            }

            string errorMsg = string.Empty;
            if (!string.IsNullOrEmpty(msg)) errorMsg += "错误消息：" + msg + Environment.NewLine;
            if (!string.IsNullOrEmpty(trace)) errorMsg += "异常跟踪：" + trace + Environment.NewLine;
            if (!string.IsNullOrEmpty(source)) errorMsg += "异常源头:" + source + Environment.NewLine;
            string error = $"出错原因：非UI线程异常 \r\nExceptionObject Types:{e.ExceptionObject.GetType()} \r\n EToString:{e.ToString()}\r\n{errorMsg}";
            LogHelper.Error(error);
        }

        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string error = $"出错原因：UI线程异常 异常消息:{e.Exception.Message} \r\n 异常跟踪:{e.Exception.StackTrace}";
            LogHelper.Error(error);
        }
    }
}
